<template>
  <view class="popup">
    <up-popup
      :show="show"
      mode="bottom"
      :closeable="true"
      @close="close"
      @open="open"
    >
      <view class="content">
        <view class="top">
          <view class="title"> 请选择服务时间 </view>
          <view class="date_box">
            <scroll-view :scroll-x="true">
              <view class="days">
                <view
                  class="day"
                  :class="[{ 'day--active': item.check }]"
                  v-for="(item, index) of $data.dayList"
                  :key="index"
                  @tap="onCheckDay(item, index)"
                >
                  <view class="day_week">{{ item.dayWeek }}</view>
                  <view class="day_date">{{ item.date }}</view>
                  <view class="day_icon" v-if="item.check">
                    <image :src="ImgIconTabGreen" mode="widthFix" />
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
        <view class="time_content">
          <scroll-view :scroll-y="true">
            <view class="time_box">
              <view
                class="time"
                :class="[
                  { 'time--out': !item.can, 'time--active': item.check },
                ]"
                v-for="(item, index) of $data.timeList"
                :key="index"
                @tap="onCheckTime(item, index)"
              >
                <view class="time_label">{{ item.time }}</view>
                <view v-if="!item.can" class="time_status">
                  {{ item.status }}
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="confirm">
          <view class="common_btn confirm_btn" @tap="onConfirm">确定</view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { reactive, ref, nextTick, computed, onMounted, watch } from "vue";
import { ImgIconTabGreen } from "../../../../utils/iconMap";
import dayjs from "dayjs";
import { times } from "../../../../uni_modules/uview-plus/libs/function/digit";
import { useGetConfig } from "../../../../hooks/useCommon";
import { configKeyEnum } from "../../../../enums/common";
import { isDev } from "../../../../utils/env";
const week = ["日", "一", "二", "三", "四", "五", "六"];
const timeBlock = [
  "7:00",
  "7:30",
  "8:00",
  "8:30",
  "9:00",
  "9:30",
  "10:00",
  "10:30",
  "11:00",
  "11:30",
  "12:00",
  "12:30",
  "13:00",
  "13:30",
  "14:00",
  "14:30",
  "15:00",
  "15:30",
  "16:00",
  "16:30",
  "17:00",
  "17:30",
  "18:00",
  "18:30",
  "19:00",
];
const $emit = defineEmits(["update:show", "close", "confirm"]);
const $props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  nowDay: {
    type: Object,
    default: () => dayjs(),
  },
});
const $data = reactive({
  dayList: [],
  timeList: [],
  send: null,
  serviceTime: 0, // 服务端校准时间
  minTime: 900,
  maxTime: 1700,
  inTime: false, // 当前时间段是否在禁止预约时间段内
  // nowDay: isDev ? dayjs("2025-08-18 22:01:01") : dayjs(),
  // nowDay: dayjs(),
});
const close = () => {
  $emit("update:show", false);
};
const open = () => {
  const nowTime = Number($props.nowDay.format("HHmm")); // 当前的时分
  $data.inTime = nowTime >= $data.maxTime || nowTime <= $data.minTime;
  formatDays();
  formatTimes();
  verTimeOut();
};
const onCheckDay = (item, index) => {
  $data.dayList.map((m, i) => (m.check = i === index));
  verTimeOut();
};
const formatDays = () => {
  $data.dayList = [];
  const today = $props.nowDay; // .format("MM月DD日");
  const DAYLEN = 31;
  const dayList = [
    {
      _dayObj: today,
      _format: today.format("YYYY/MM/DD"),
      _year: today.year(),
      date: today.format("MM月DD日"),
      dayWeek: week[today.day()],
      check: true,
      dayType: "today",
    },
  ];
  for (var i = 1; i < DAYLEN; i++) {
    const tomorrow = today.add(i, "day");
    const date = tomorrow.format("MM月DD日");
    const dayWeek = week[tomorrow.day()];
    let dayType = null;
    if (i === 1) {
      dayType = "tomorrow";
    }
    dayList.push({
      _dayObj: tomorrow,
      _format: tomorrow.format("YYYY/MM/DD"),
      _year: tomorrow.year(),
      date,
      dayWeek,
      check: false,
      dayType,
    });
  }
  $data.dayList = dayList;
  // console.log("formatDays", dayList);
};
const onCheckTime = (item, index) => {
  verTimeOut();
  if (!item.can) return;
  $data.timeList.map((m, i) => (m.check = i === index));
  const dayItem = $data.dayList.find((d) => d.check);
  const { _format, _year, date } = dayItem;
  const { time } = item;
  const checkTimeStamp = dayjs(`${_format} ${time}`).unix(); //.valueOf();
  const label = `${_year}年${date} ${time}`;
  $data.send = {
    time: checkTimeStamp,
    label,
  };
};
const formatTimes = () => {
  const timeList = [];
  for (var i = 7; i <= 19; i++) {
    timeList.push({
      time: `${i}:00`,
      status: null,
      check: false,
      num: Number(`${i}00`),
    });
    if (i !== 19) {
      timeList.push({
        time: `${i}:30`,
        status: null,
        check: false,
        num: Number(`${i}30`),
      });
    }
  }
  $data.timeList = timeList;
  console.log("timeList", timeList);
};
/** 校验时间是否过期 */
const verTimeOut = () => {
  const dayItem = $data.dayList.find((d) => d.check);
  const { _format, dayType } = dayItem;
  const nowTimeStamp = $props.nowDay.add($data.serviceTime, "minute").unix();
  // 1.当前时间处在禁约时段中
  if ($data.inTime) {
    const nowTime = Number($props.nowDay.format("HHmm"));
    console.log("nowTime", nowTime);
    $data.timeList.forEach((item) => {
      const { time, num } = item;
      const itemTimeStamp = dayjs(`${_format} ${time}`).unix();
      let not = true; // 是否不可约
      // 白天
      if (nowTime >= 0 && nowTime <= $data.minTime) {
        // not = num <= $data.minTime;
        if (dayType === "today") {
          not = num <= $data.minTime;
        } else if (dayType === "tomorrow") {
          not = false;
        } else {
          not = false;
        }
      }
      // 夜晚
      else if (nowTime >= $data.maxTime && nowTime <= 2359) {
        if (dayType === "today") {
          not = num >= $data.maxTime || num <= $data.maxTime;
        } else if (dayType === "tomorrow") {
          not = num <= $data.minTime;
        } else {
          not = false;
        }
      }
      item.status = not || nowTimeStamp > itemTimeStamp ? "约满" : null;
      item.can = !(not || nowTimeStamp > itemTimeStamp);
      item.check = false;
    });
  }
  // 2.当前时间不在禁约时段
  else {
    $data.timeList.forEach((item) => {
      const { time } = item;
      const itemTimeStamp = dayjs(`${_format} ${time}`).unix();
      item.status = nowTimeStamp > itemTimeStamp ? "约满" : null;
      item.can = !(nowTimeStamp > itemTimeStamp);
      item.check = false;
    });
  }
};
const onConfirm = () => {
  $emit("confirm", $data.send);
  close();
};
onMounted(async () => {
  await useGetConfig({ key: configKeyEnum["用户服务时间校准参数"] }).then(
    (res) => {
      // 单位分钟
      $data.serviceTime = Number(res || 0);
      // console.log("$data.serviceTime", $data.serviceTime);
    }
  );
  await useGetConfig({ key: configKeyEnum["禁止预约时间"] }).then((res) => {
    if (res && res.length > 0) {
      // const one = { value: "21:00" };
      // const two = { value: "9:00" };
      const one = res[0];
      const two = res[1];
      if (one.value) {
        const [h, m] = one.value.split(":");
        $data.maxTime = Number(h + m);
      }
      if (two.value) {
        const [h, m] = two.value.split(":");
        $data.minTime = Number(h + m);
      }
      const nowTime = Number($props.nowDay.format("HHmm")); // 当前的时分
      $data.inTime = nowTime >= $data.maxTime || nowTime <= $data.minTime;
    }
  });
  formatDays();
  formatTimes();
  verTimeOut();
});
watch(
  () => $props.nowDay,
  (n, o) => {
    try {
      if (n) {
        console.log("choose time watch", n);
        const nowTime = Number(n.format("HHmm")); // 当前的时分
        $data.inTime = nowTime >= $data.maxTime || nowTime <= $data.minTime;
        formatDays();
        formatTimes();
        verTimeOut();
      }
    } catch (e) {}
  },
  {
    immediate: false,
  }
);
// onMounted(async () => {
//   await useGetConfig({ key: configKeyEnum["用户服务时间校准参数"] }).then(
//     (res) => {
//       // 单位分钟
//       $data.serviceTime = Number(res || 0);
//       // console.log("$data.serviceTime", $data.serviceTime);
//     }
//   );
//   await useGetConfig({ key: configKeyEnum["禁止预约时间"] }).then((res) => {
//     if (res && res.length > 0) {
//       // const one = { value: "21:00" };
//       // const two = { value: "9:00" };
//       const one = res[0];
//       const two = res[1];
//       if (one.value) {
//         const [h, m] = one.value.split(":");
//         $data.maxTime = Number(h + m);
//       }
//       if (two.value) {
//         const [h, m] = two.value.split(":");
//         $data.minTime = Number(h + m);
//       }
//       const nowTime = Number($data.nowDay.format("HHmm")); // 当前的时分
//       $data.inTime = nowTime >= $data.maxTime || nowTime <= $data.minTime;
//     }
//   });
//   formatDays();
//   formatTimes();
//   verTimeOut();
// });
</script>
<script>
// 小程序穿透
export default {
  options: { styleIsolation: "shared" },
};
</script>
<style lang="scss" scoped>
.popup {
  ::v-deep .u-popup__content {
    border-radius: 30rpx 30rpx 0 0 !important;
    height: 80vh;
  }
  ::v-deep .u-popup__content__close {
    z-index: 999999;
  }
  .content {
    background: #ffffff;
    border-radius: 30rpx 30rpx 0 0;
    height: 80vh;
    .top {
      background: #ffffff;
      position: sticky;
      top: 0;
      z-index: 9999;
      height: 18vh;
    }
    .title {
      background: #ffffff;
      padding: 30rpx;
      font-size: 36rpx;
      border-bottom: 1px solid #f0f0f0;
    }
    .date_box {
      display: flex;
      justify-content: center;
      width: 100vw;
      margin-top: 30rpx;
      padding: 0 30rpx;
      height: 130rpx;
      scroll-view {
        white-space: nowrap;
        width: 100%;
        .days {
          display: flex;
          align-items: center;
          width: 100%;
          .day {
            font-size: 34rpx;
            width: 140rpx; //calc(100% / 5);
            color: #999999;
            position: relative;
            // display: flex;
            // flex-direction: column;
            // justify-content: center;
            // align-items: center;
            &:not(:last-child) {
              margin-right: 30rpx;
            }
            &_week {
              text-align: center;
              margin-bottom: 10rpx;
            }
            &_date {
              text-align: center;
              font-size: 30rpx;
              width: 140rpx;
            }
            &_icon {
              position: absolute;
              left: 0;
              right: 0;
              bottom: -14rpx;
              margin: auto;
              width: 30rpx;
              height: 20rpx;
              z-index: 9;
              image {
                width: 100%;
                height: 100%;
              }
            }
          }
          .day--active {
            color: #333333;
          }
        }
      }
    }
    .time_content {
      margin-top: 30rpx;
      padding: 0 30rpx 30rpx 30rpx;
      scroll-view {
        width: 100%;
        height: 50vh;
      }
      .time_box {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        width: 100%;
        overflow: auto;
      }
      .time {
        width: calc(94% / 4);
        height: 170rpx;
        border-radius: 15rpx;
        background: #ffffff;
        border: 1px solid #cccccc;
        font-size: 34rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-bottom: 14rpx;
        &:not(:nth-of-type(4n)) {
          margin-right: 2%;
        }
        &_label {
          //   font-weight: 700;
          text-align: center;
        }
        &_status {
          text-align: center;
          font-size: 32rpx;
          margin-top: 10rpx;
        }
      }
      .time--out {
        background: #f5f5f5;
        color: #999999;
      }
      .time--active {
        border: 1px solid $main-color;
        color: $main-color;
        background: #e4f9f9;
      }
    }
    .confirm {
      width: 100%;
      height: 10vh;
      //   margin: 30rpx 0;
      padding: 30rpx;
      background: #ffffff;
      z-index: 9999;
      position: fixed;
      bottom: 10rpx;
      &_btn {
        width: 100%;
      }
    }
  }
}
</style>
